﻿using Autofac;
using AutoMapper;
using Common.Model;
using Common.Tools;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using MyBlog.Common;
using MyBlog.IService;
using MyBlog.Model.Entity;
using MyBlog.Model.ViewModels;
using MyBlog.Service;
using System;
using System.Diagnostics;
using System.Security.Claims;
using System.Security.Cryptography;

namespace MyBlog.Controllers
{
    public class UserController : Controller
    {
        private ILogger<UserController> _logger;
        private IUserService _userService;
        private IUserBlogInfoService _userBlogInfoService;
        private IMapper _mapper;
        private IMemoryCache _cache;
        public UserController(ILogger<UserController> logger, IComponentContext componentContext, IMapper mapper, IMemoryCache cache)
        {
            _userService = componentContext.Resolve<IUserService>();
            _userBlogInfoService = componentContext.Resolve<IUserBlogInfoService>(); ;
            this._logger = logger;
            _mapper = mapper;
            _cache = cache;
        }
        /// <summary>
        /// 个人主页
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Index(int id)
        {
            User user = await _userService.FindAsync(id);
            UserBlogInfo ubi = await _userBlogInfoService.FindAsync(id);
            HomePageViewModel model = new HomePageViewModel()
            {
                UserId = id,
                Name = user.Name,
                Photo = "logo.jpg",
                BlogCount = ubi.BlogCount,
                PageView = ubi.PageView
            };
            return View(model);
        }

        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login(LoginUser model)
        {
            try
            {
                ApiResult apiResult = new ApiResult()
                {
                    Success = true,
                    Message = "登录成功"
                };
                var currCode = _cache.Get("CaptchaCode");
                if (currCode?.ToString().ToLower() != model.CaptchaCode)
                {
                    apiResult.Success = false;
                    apiResult.Message = "验证码错误";
                    return new JsonResult(apiResult);
                }
                _logger.LogInformation($"用户登录");
                var users = (await _userService.QueryAsync(u => u.Name == model.Name && u.Password == model.Password));
                if (users == null)
                {
                    apiResult.Success = false;
                    apiResult.Message = "用户名或密码错误";
                    return new JsonResult(apiResult);
                }
                var user = users.FirstOrDefault();
                if (user == null)
                {
                    apiResult.Success = false;
                    apiResult.Message = "用户名或密码错误";
                    return new JsonResult(apiResult);
                }
                //以下Claim可以写入任意数据
                var claims = new List<Claim>()//用于鉴别当前用户相关信息
                    {
                        new Claim("Id",user.Id.ToString()),
                        new Claim(ClaimTypes.Name,user.Name),//标记该用户名
                        new Claim(ClaimTypes.Email,user.Email),//标记该用户邮箱
                        new Claim("password",user.Password),
                        new Claim("NickName",user.NickName),
                        new Claim("Phone",user.Phone)
                    };
                ClaimsPrincipal userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer")); 
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(10)//过期时间为1分钟
                }).Wait();

               
                _logger.LogInformation($"用户[{user.Name}]登录成功");
                return new JsonResult(apiResult);
            }
            catch (Exception ex)
            {
                _logger.LogError("登录发生异常：" + ex.Message);
                throw new Exception("登录发生异常：" + ex.Message);
            }
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Exit()
        {
            HttpContext.SignOutAsync();
            string name = HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
            _logger.LogInformation($"用户 {name}退出登录");
            return RedirectToAction("Login", "User");
        }
        [HttpGet]
        public IActionResult GetCaptchaImage()
        {
            Tuple<string, int> captchaCode = CaptchaHelper.GetCaptchaCode();
            byte[] bytes = CaptchaHelper.CreateCaptchaImage(captchaCode.Item1);
            _cache.Set<int>("CaptchaCode", captchaCode.Item2);
            return File(bytes, @"image/jpeg");
        }

        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Register(UserViewModel model)
        {
            if (await _userService.AddAsync(model))
            {
                _logger.LogInformation($"用户{model.Name}注册成功");
                return Json(new { status = 0, msg = "注册成功" });
            }
            _logger.LogInformation($"用户{model.Name}注册失败");
            return Json(new { status = 1, msg = "注册失败" });
        }

        [HttpGet]
        [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
        public async Task<IActionResult> Personal()
        {
            //    ViewBag.Title = "个人中心";
            //    string id = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "Id")?.Value;
            //    if (id == null)
            //        return Redirect("/User/Login");

            //    string name = HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
            //    User user =await _userService.FindAsync(Convert.ToInt32(id));
            //    if (user == null) return Redirect("/User/Login");
            //    //UserViewModel model = new UserViewModel
            //    //{
            //    //    Id = user.Id,
            //    //    Name = user.Name,
            //    //    NickName = user.NickName,
            //    //    Email = user.Email,
            //    //    Phone = user.Phone,
            //    //    Password = user.Password
            //    //};
            //    ModifyUserViewModel model= _mapper.Map<ModifyUserViewModel>(user);
            //    return View(model);
            return View();
        }
        [HttpPost]
        [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
        public async Task<IActionResult> UserInfo()
        {
            string id = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "Id")?.Value;
            if (id == null)
                return Redirect("/User/Login");

            string name = HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
            User user = await _userService.FindAsync(Convert.ToInt32(id));
            if (user == null) return Redirect("/User/Login");
            //UserViewModel model = new UserViewModel
            //{
            //    Id = user.Id,
            //    Name = user.Name,
            //    NickName = user.NickName,
            //    Email = user.Email,
            //    Phone = user.Phone,
            //    Password = user.Password
            //};
            ModifyUserViewModel model = _mapper.Map<ModifyUserViewModel>(user);


            ApiDataResult<ModifyUserViewModel> apiDataResult = new ApiDataResult<ModifyUserViewModel>()
            {
                Data = model,
                Success = true,
                Message = "获取个人信息成功"
            };
            return new JsonResult(apiDataResult);
        }

        [HttpPost]
        [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
        public async Task<IActionResult> Modify(ModifyUserViewModel model)
        {
            ApiResult apiResult = new ApiResult()
            {
                Success = true,
                Message = "修改个人信息成功"
            };
            try
            {
                User user = _mapper.Map<User>(model);
                string pwd = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "password")?.Value;
                user.Password = pwd;
                bool bRet = await _userService.ModifyAsync(user);
                if (!bRet)
                {
                    apiResult.Success = false;
                    apiResult.Message = "修改个人信息失败";
                }
            }
            catch (Exception ex)
            {
                apiResult.Success = false;
                apiResult.Message = "修改个人信息失败:" + ex.Message;
            }

            return new JsonResult(apiResult);
        }

        public IActionResult PersonBlogList(int userId, EnumBlogBrowseType type)
        {
            ViewBag.UserId = userId;
            ViewBag.Type = type;
            return View();
        }
    }
}
